// ;
// (function() {
// 	var uid = "dianna";
// 	var key = "02735530a760a26e55af";
// 	var sms = {
// 		send: function(phone_num, content) {
// 			console.log("http://utf8.sms.webchinese.cn/?Uid=" + uid + "&Key=" + key + "&smsMob=" + phone_num + "&smsText=" + content);
// 			var result = curl("http://utf8.sms.webchinese.cn/?Uid=" + uid + "&Key=" + key + "&smsMob=" + phone_num + "&smsText=" + content);
// 			switch (result) {
// 				case "-1":
// 					throw "没有该用户账户";
// 				case "-2":
// 					throw "接口密钥不正确";
// 				case "-21":
// 					throw "MD5接口密钥加密不正确";
// 				case "-3":
// 					throw "短信数量不足";
// 				case "-11":
// 					throw "该用户被禁用";
// 				case "-14":
// 					throw "短信内容出现非法字符";
// 				case "-4":
// 					throw "手机号格式不正确";
// 				case "-41":
// 					throw "手机号码为空";
// 				case "-42":
// 					throw "短信内容为空";
// 				case "-51":
// 					throw "短信签名格式不正确";
// 				case "-6":
// 					throw "IP限制";
// 				default:
// 					console.log("短信发送日志：", result);
// 					result = parseInt(result);
// 					if (result > 0) {
// 						console.log("短信发送成功", phone_num);
// 						return true;
// 					} else {
// 						throw "未知错误"
// 					}
// 			}
// 		}
// 	};
// 	module.exports = sms;
// }());

var request = require("request");
var Fiber = require('fibers');
var helper = require("./helper");
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; //证书过期也不管

module.exports = {
	send: function(phone_num, content) {
		if (!helper.phone(phone_num)) {
			throwCusError("手机号格式不正确")
		}
		var fiber = Fiber.current;
		console.log("SMS:", content);
		var options = {
			url: 'https://api.bmob.cn/1/requestSms',
			headers: {
				"X-Bmob-Application-Id": "1bb9956f89105fc8317a134a61bd4c79",
				"X-Bmob-REST-API-Key": "3f9022c11b6af173a8f57187e8033081",
				"Content-Type": "application/json"
			},
			method: "POST",
			body: JSON.stringify({
				mobilePhoneNumber: phone_num,
				content: content
			})
		};
		var result = false;
		request(options, function(error, response, body) {
			try {
				var res = JSON.parse(body)
				if (res.error) {
					console.error(res.error);
				} else {
					console.log("短信发送成功", phone_num);
					result = true;
				}
			} catch (e) {
				console.error("未知错误：" + body);
			}
			console.log(response.statusCode, body);
			fiber && fiber.run();
		});
		Fiber.yield(); //挂起
		return result;
	}
}